<!--
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-08 21:23:56
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-03-30 22:58:32
 * @FilePath: /ai-interview-vue/src/views/Home/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <div class="home">
        <div class="chat-container">
            <!-- AI头像 -->
            <div class="ai-avatar">
                <img src="/images/mine/ai-avatar.png" alt="AI助手">
            </div>

            <!-- 对话历史区域 -->
            <div class="chat-history">
                <!-- 各个阶段的消息 -->
                <div v-for="(message, index) in chatMessages" :key="index" class="message-block">
                    <!-- AI消息 -->
                    <div v-if="message.type === 'ai'" class="ai-message">
                        <div class="text">{{ message.content }}</div>
                    </div>

                    <!-- 简历上传组件 -->
                    <div v-if="message.type === 'resume_upload' && showUpload" class="upload-block"
                        @click="goToUploadResume">
                        <div class="card-content">
                            <van-icon name="plus" />
                            <span>点击上传简历</span>
                        </div>
                    </div>

                    <!-- 简历信息 -->
                    <div v-if="message.type === 'resume'" class="file-card">
                        <div class="file-info">
                            <img src="/images/mine/resume/resume-icon.png" alt="简历" class="file-icon" />
                            <div class="file-details">
                                <span class="file-name">{{ message.content.cv_name }}</span>
                                <span class="change-btn" @click="handleUploadResume">更换</span>
                            </div>
                        </div>
                    </div>

                    <!-- 岗位选择组件 -->
                    <div v-if="message.type === 'job_select'" class="action-card" @click="goToAddJob">
                        <div class="card-content">
                            <van-icon name="plus" />
                            <span>添加面试岗位</span>
                        </div>
                        <!-- <file-upload :upload-tip="'请选择职位类型'" @file-selected="handleFileSelected"
                            @upload-success="handleUploadSuccess" /> -->
                    </div>

                    <!-- 岗位信息 -->
                    <div v-if="message.type === 'job'" class="job-card">
                        <div class="job-info">
                            <img src="/images/mine/jobs/interviews-icon.png" alt="岗位" class="job-icon" />
                            <div class="job-details">
                                <span class="job-name">{{ message.content.jd_title }}</span>
                                <span class="change-btn" @click="handleSelectJob">更换</span>
                            </div>
                        </div>
                    </div>

                    <!-- 开始面试按钮 -->
                    <div v-if="message.type === 'start_button'" class="start-button">
                        <van-button block type="primary" v-loading="handleStartInterview">
                            开始免费面试
                        </van-button>
                    </div>
                    <!-- 面试结束 -->
                    <div v-if="message.type === 'interview_result'" class="interview-duration-card">
                        <div class="action-buttons">
                            <div class="notice">注意：面试时长超过30分钟才能查看面试结果和分析</div>
                            <div class="action-item" @click="handleInviteFriends">
                                <span>邀请好友助力得10分钟面试时长</span>
                                <span class="arrow-icon">
                                    <van-icon name="arrow" />
                                </span>
                            </div>

                            <div class="action-item" @click="handleRecharge">
                                <span>立即充值，30分钟仅需6元</span>
                                <span class="arrow-icon">
                                    <van-icon name="arrow" />
                                </span>
                            </div>
                        </div>
                        <div class="interview-result-card">
                            <div class="result-card">
                                <div>面试得分：<span class="score">{{ message.content.average_score
                                        }}</span></div>
                                <div class="result-item">面试岗位：<span class="position">{{ message.content.jd_title
                                        }}</span>
                                </div>
                                <div>面试时间：<span class="date">{{ message.content.created_at }}</span>
                                </div>
                                <div class="action-buttons">
                                    <van-button class="check-btn" type="primary" block
                                        @click="handleView(message.content)">查看详细结果</van-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 当前正在输入的消息 -->
                <div v-if="isTyping" class="ai-message">
                    <div class="text">
                        {{ currentMessage }}
                        <span class="cursor">|</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, onMounted, computed, onActivated, onDeactivated, onBeforeUnmount } from 'vue'
    import { useRouter } from 'vue-router'
    import { resumeApi } from '@/api/resume'
    import { jobApi } from '@/api/job'
    import FileUpload from '@/components/FileUpload/index.vue'
    import { showToast, closeToast } from 'vant'
    import { uploadFiles } from '@/api/comm'
    import { useInterviewStore } from '@/store/modules/interview'
    import { interviewApi } from '@/api/interview'
    import emitter from '@/utils/eventBus'

    const router = useRouter()
    const interviewStore = useInterviewStore()
    const currentMessage = ref('')
    const isTyping = ref(false)
    const currentStage = ref('WELCOME')
    const chatMessages = ref([])
    const showUpload = ref(true)
    const uploadType = ref('')
    const initData = reactive({
        cv_id: '',
        jd_id: ''
    })
    // 是否面试过
    const hasInterviewed = ref(false)
    // 记录上一次的路由
    const lastRoute = ref('')

    // 监听简历文件上传事件
    emitter.on('resume-file-upload', async (file) => {
        console.log('接收到上传的简历文件:', file)
        await handleResumeFileUpload(file)
    })

    // 组件卸载前移除事件监听
    onBeforeUnmount(() => {
        emitter.off('resume-file-upload')
    })

    // 对话内容配置
    const DialogContent = {
        WELCOME: '你好!我是AI面试官小橙,很高兴见到你!',
        NO_RESUME: '我看到你还没有上传简历,上传简历后我们就可以开始模拟面试了',
        RESUME_UPLOADED: '太好了!我已经收到你的简历了',
        NO_JOB: '接下来请选择你想要面试的岗位',
        JOB_SELECTED: '好的,职位已选择完成',
        READY: '准备好了吗?点击下方按钮开始模拟面试吧!',
        INTERVIEW_END: '面试的还不错嘛!如果需要继续模拟面试帮助，可以用以下办法获得面试时长哦',
    }

    // 添加消息到历史记录
    const addMessage = (type, content) => {
        chatMessages.value.push({ type, content })
    }

    // 打字机效果
    const typeMessage = async (text, speed = 100) => {
        isTyping.value = true
        currentMessage.value = ''

        for (let char of text) {
            currentMessage.value += char
            await new Promise(resolve => setTimeout(resolve, speed))
        }

        addMessage('ai', currentMessage.value)
        currentMessage.value = ''
        isTyping.value = false
    }

    // 组件激活时的处理
    onActivated(async () => {
        // 如果是从面试页面返回，需要重新初始化

        if (lastRoute.value.includes('/interview/voice')) {
            chatMessages.value = [] // 清空之前的消息
            // await typeMessage(DialogContent.WELCOME)
            await checkStatusAndUpdateDialog()
            return
        }
        // 如果是从简历页面返回，重新查询默认简历
        if (lastRoute.value.includes('/profile/resume')) {
            await checkDefaultResume()
        }

        // 如果是从岗位页面返回，重新查询默认岗位
        if (lastRoute.value.includes('/profile/jobs')) {
            await checkDefaultJob()
        }
        // 如果是从简历或岗位页面返回，只需要重新检查状态
        if (lastRoute.value.includes('/profile/resume') || lastRoute.value.includes('/profile/jobs') || lastRoute.value.includes('/profile/mine')) {
            // 保存当前消息
            const currentMessages = [...chatMessages.value]



            console.log(currentStage.value, "currentStage.value")
            // 如果状态没有变化，恢复之前的消息
            if (currentStage.value === 'NO_RESUME' || currentStage.value === 'NO_JOB') {
                chatMessages.value = currentMessages
            }
            if (hasInterviewed.value) {
                currentStage.value = 'INTERVIEW_END'
                // 如果不是从其他页面返回，才显示欢迎消息
                if (!lastRoute.value) {
                    await typeMessage(DialogContent.INTERVIEW_END)
                }
            }
        }
    })

    // 组件停用时的处理
    onDeactivated(() => {
        // 记录当前路由，用于判断返回场景
        lastRoute.value = router.currentRoute.value.path
        console.log(lastRoute.value, "lastRoute.value")
        // 清理打字机效果的状态
        if (isTyping.value) {
            currentMessage.value = ''
            isTyping.value = false
        }
    })

    // 检查状态并更新对话
    const checkStatusAndUpdateDialog = async () => {
        try {
            // 直接使用 store 中的状态，不重复调用 API
            hasInterviewed.value = interviewStore.hasInterviewed
            console.log(hasInterviewed.value, "hasInterviewed.value")
            if (hasInterviewed.value) {
                currentStage.value = 'INTERVIEW_END'
                // 如果不是从其他页面返回，才显示欢迎消息
                if (!lastRoute.value) {
                    await typeMessage(DialogContent.INTERVIEW_END)
                }
                addMessage('interview_result', interviewStore.interviewResult)
                return
            }

            // 如果已经是准备面试状态，不需要重复处理
            if (currentStage.value === 'READY') {
                return
            }

            // 等待欢迎语完成后的短暂停顿
            if (!lastRoute.value) {
                await new Promise(resolve => setTimeout(resolve, 500))
            }

            // 检查是否有默认简历
            const hasResume = await checkDefaultResume()
            if (!hasResume) return

            // 等待简历相关对话完成后的短暂停顿
            await new Promise(resolve => setTimeout(resolve, 500))

            // 检查是否有默认岗位
            const hasJob = await checkDefaultJob()
            console.log(hasJob, "hasJob")
            if (!hasJob) return

            // 准备面试
            currentStage.value = 'READY'
            await typeMessage(DialogContent.READY)
            addMessage('start_button', null)
        } catch (error) {
            console.error('检查状态失败:', error)
        }
    }

    // 处理上传简历
    const handleUploadResume = () => {
        router.push({
            path: '/profile/resume',
            query: {
                type: 'create'
            }
        })
    }

    // 处理选择岗位
    const handleSelectJob = () => {
        router.push({
            path: '/profile/jobs',
            query: {
                type: 'create'
            }
        })
    }

    // 开始面试
    const handleStartInterview = async () => {

        // 创建面试
        const res = await interviewApi.createInit({
            cv_id: initData.cv_id,
            jd_id: initData.jd_id
        })

        if (res.data?.interview_record_id) {
            router.push({
                path: '/interview/voice',
                query: {
                    interview_record_id: res.data.interview_record_id
                }
            })
        }
    }

    // 处理上传成功
    const handleUploadSuccess = () => {
        showUpload.value = false
        checkStatusAndUpdateDialog()
    }
    // 查看面试结果
    const handleView = (message) => {
        router.push({
            path: `/profile/interviews/detail`,
            query: {
                id: message.id
            }
        })
    }
    // 跳转到上传简历页面
    const goToUploadResume = () => {
        router.push('/profile/resume/create')
    }
    // 跳转到添加岗位页面
    const goToAddJob = () => {
        router.push('/profile/jobs/create')
    }

    // 邀请好友助力
    const handleInviteFriends = () => {
        // router.push('/profile/invite')
        showToast('敬请期待')
    }
    // 立即充值
    const handleRecharge = () => {
        // router.push('/profile/recharge')
        showToast('敬请期待')
    }

    // 处理从简历上传页面传递过来的文件
    const handleResumeFileUpload = async (file) => {

        try {
            // 显示上传中提示
            showToast({
                type: 'loading',
                message: '上传中...',
                forbidClick: true,
                duration: 0
            });

            // 上传文件
            const res = await uploadFiles(file);

            // 创建简历记录
            await resumeApi.editResume({
                cv_name: file.name,
                cv_url: res.data.url,
                default_status: 1 // 默认状态:0=非默认,1=默认
            });

            // 关闭提示
            closeToast()
            showToast('上传成功');

            // 重新检查状态并更新对话
            showUpload.value = false;
            await checkStatusAndUpdateDialog();
        } catch (error) {
            console.error('上传失败:', error);
            showToast('上传失败，请重试');
        }
    };

    // 组件挂载时开始对话
    onMounted(async () => {
        await typeMessage(DialogContent.WELCOME)
        await checkStatusAndUpdateDialog()
    })

    // 检查默认简历
    const checkDefaultResume = async () => {
        try {
            // 检查是否有默认简历
            const resumeRes = await resumeApi.getDefaultResume()
            const hasResume = resumeRes.data && resumeRes.data.length > 0

            if (!hasResume) {
                currentStage.value = 'NO_RESUME'
                // 清除之前的简历相关消息
                chatMessages.value = chatMessages.value.filter(msg => msg.type !== 'resume')
                // 添加上传简历提示
                if (!chatMessages.value.some(msg => msg.type === 'resume_upload')) {
                    await typeMessage(DialogContent.NO_RESUME)
                    addMessage('resume_upload', null)
                }
                return false
            } else {
                initData.cv_id = resumeRes.data[0].id
                // 更新或添加简历卡片
                const resumeIndex = chatMessages.value.findIndex(msg => msg.type === 'resume')
                if (resumeIndex >= 0) {
                    chatMessages.value[resumeIndex].content = resumeRes.data[0]
                } else {
                    addMessage('resume', resumeRes.data[0])
                    await new Promise(resolve => setTimeout(resolve, 300))
                    await typeMessage(DialogContent.RESUME_UPLOADED)
                }
                return true
            }
        } catch (error) {
            console.error('检查默认简历失败:', error)
            return false
        }
    }

    // 检查默认岗位
    const checkDefaultJob = async () => {
        try {
            // 检查是否有默认岗位
            const jobRes = await jobApi.getDefaultJob({ default_status: 1 })
            const hasJob = jobRes.data && jobRes.data.length > 0

            if (!hasJob) {
                currentStage.value = 'NO_JOB'
                // 清除之前的岗位相关消息
                chatMessages.value = chatMessages.value.filter(msg => msg.type !== 'job')
                // 添加选择岗位提示
                if (!chatMessages.value.some(msg => msg.type === 'job_select')) {
                    await typeMessage(DialogContent.NO_JOB)
                    addMessage('job_select', null)
                }
                return false
            } else {
                initData.jd_id = jobRes.data[0].id
                // 更新或添加岗位卡片
                const jobIndex = chatMessages.value.findIndex(msg => msg.type === 'job')
                if (jobIndex >= 0) {
                    chatMessages.value[jobIndex].content = jobRes.data[0]
                } else {
                    addMessage('job', jobRes.data[0])
                    await new Promise(resolve => setTimeout(resolve, 300))
                    await typeMessage(DialogContent.JOB_SELECTED)
                }
                return true
            }
        } catch (error) {
            console.error('检查默认岗位失败:', error)
            return false
        }
    }

    const handlePositionSelect = async (position) => {
        if (currentStage.value === 'READY') {
            return
        }
        selectedPosition.value = position
        currentStage.value = 'READY'
        await typeMessage(DialogContent.READY)
        addMessage('start_button', null)
    }
</script>

<style lang="scss" scoped>
    .home {
        min-height: 100vh;
        background: rgba(255, 255, 255, 1);
        padding: 16px;

        .chat-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .ai-avatar {
            text-align: center;
            margin-bottom: 24px;

            img {
                width: 80px;
                height: 80px;
                border-radius: 50%;
            }
        }

        .chat-history {
            .message-block {
                margin-bottom: 10px;
            }

            .ai-message {
                background: #fff;
                padding: 0 16px;
                border-radius: 12px;

                .text {
                    font-size: 20px;
                    line-height: 1.6;
                    color: #333;
                    font-weight: 500;
                }
            }

            .upload-block {
                margin: 16px 0;
                background: #fff;
                border-radius: 12px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
                overflow: hidden;
                padding: 20px;

                .card-content {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    color: rgba(29, 33, 41, 1);
                    font-size: 17px;

                    .van-icon {
                        font-size: 18px;
                        margin-right: 8px;
                    }
                }
            }

            .file-card,
            .job-card {
                background: #fff;
                border-radius: 12px;
                padding: 16px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

                .file-info,
                .job-info {
                    display: flex;
                    align-items: center;
                    gap: 12px;

                    .file-icon,
                    .job-icon {
                        width: 40px;
                        height: 40px;
                    }

                    .file-details,
                    .job-details {
                        flex: 1;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .file-name,
                        .job-name {
                            font-size: 16px;
                            color: #333;
                            font-weight: 500;
                            width: 200px;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }

                        .change-btn {
                            color: #165dff;
                            font-size: 14px;
                            padding: 4px 12px;
                            border-radius: 4px;
                            background: rgba(22, 93, 255, 0.1);
                            cursor: pointer;
                            transition: all 0.3s;

                            &:hover {
                                background: rgba(22, 93, 255, 0.15);
                            }
                        }
                    }
                }
            }
        }

        .cursor {
            display: inline-block;
            width: 2px;
            height: 16px;
            background-color: #333;
            margin-left: 2px;
            animation: blink 1s infinite;
        }

        .upload-section {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #fff;
            z-index: 100;
            animation: slideUp 0.3s ease;
        }

    }

    @keyframes blink {

        0%,
        100% {
            opacity: 1;
        }

        50% {
            opacity: 0;
        }
    }

    @keyframes slideUp {
        from {
            transform: translateY(100%);
        }

        to {
            transform: translateY(0);
        }
    }

    .action-card {
        margin-top: 20px;
        background: #fff;
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        cursor: pointer;
        background: rgba(242, 243, 245, 1);

        .card-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: rgba(29, 33, 41, 1);

            .van-icon {
                font-size: 32px;
                margin-bottom: 8px;
            }
        }
    }

    /* 面试结束 */
    .interview-duration-card {
        .notice {
            font-size: 12px;
            color: #999;
            color: rgba(78, 89, 105, 1);
        }

        .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 12px;
            background: rgba(242, 243, 245, 1);
            border-radius: 12px;
            padding: 12px;
        }

        .action-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            padding: 14px;
            border-radius: 8px;
            cursor: pointer;
            color: rgba(29, 33, 41, 1);
            font-size: 15px;
            font-weight: 500;
        }

        .arrow-icon {
            color: #999;
            background: rgb(242, 243, 245);
            width: 20px;
            height: 20px;
            border-radius: 50%;
            text-align: center;
            line-height: 20px;
        }
    }

    /* 面试结果 */
    .interview-result-card {
        background: rgba(242, 243, 245, 1);
        padding: 12px;
        margin-top: 12px;
        border-radius: 20px;

        .result-card {
            width: 100%;
            border-radius: 12px;
            background: rgb(255, 255, 255);
            padding: 16px;
            font-size: 17px;
            color: rgba(29, 33, 41, 1);

            .result-item {
                margin: 10px 0;
            }

            .score {
                font-size: 32px;
                font-weight: 700;
                color: rgba(22, 93, 255, 1);
            }

            .position,
            .date {
                color: #666;
                margin-bottom: 8px;
            }

            .action-buttons {
                display: flex;
                flex-direction: column;
                gap: 12px;
                margin-top: 10px;
                background: #ffff;

                .restart-btn {
                    background: #f5f5f5;
                    color: #333;
                }
            }
        }
    }
</style>